package marker.micro.login.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import marker.micro.login.entity.User;
import marker.micro.login.repository.UserRepository;

@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userrepository;

    @Override
    public UserDetails loadUserByUsername(String username)
	    throws UsernameNotFoundException {
	User user = userrepository.findByUsername(username);
	if(user==null) {
	    throw new UsernameNotFoundException(String.format("No user found with '%s'.", username));
	} else {
	    return SecurityUserFactory.create(user);
	}
    }

    public boolean registry(User newuser) {
	User user = userrepository.findByUsername(newuser.getUsername());
	if(user!=null) {
	    System.out.println("用户已存在");
	    return false;
	} else {
	    userrepository.save(newuser);
	    return true;
	}
    }
    
    public List<User> getUsers() {
	return userrepository.findAll();
    }
    
}
